package com.yokead.controller.visitors;

import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.OrderListBaseController;
import com.yokead.common.interceptor.NotLogin;
import com.yokead.i.CoverInfo;
import com.yokead.service.order.OrderService;
import com.yokead.service.order.ProductService;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by jiangzeyin on 2017/9/25.
 */
@Controller
@RequestMapping("visitors")
public class VisitorsIndexControl extends OrderListBaseController {
    public final static HashMap<String, CoverInfo> coverInfoHashMap = new HashMap<>();

    static {
        coverInfoHashMap.put("address", src -> {
            if (StringUtil.isEmpty(src))
                return null;
            if (src.contains(","))
                return src.substring(0, src.indexOf(","));
            if (src.contains(" "))
                return src.substring(0, src.indexOf(" "));
            if (src.length() >= 4)
                return src.substring(0, 4);
            return "地址不详";
        });
    }

    @Resource
    private OrderService orderService;

    @Resource
    private ProductService productService;

    @RequestMapping(value = {"", "/", "index.html"}, method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String index(String name) {
        name = convertFilePath(name);
        String sKey = StringUtil.convertNULL(getSessionAttribute("Visitors_User"));
        if (StringUtil.isEmpty(sKey))
            return "redirect:/visitors/login.html?name=" + name;
        String[] tempS = StringUtil.stringToArray(sKey, "@");
        if (tempS == null || tempS.length != 2)
            return "redirect:/visitors/login.html?name=" + name;
        if (!name.equals(tempS[0]))
            return "redirect:/visitors/login.html?name=" + name;
        JSONArray list = (JSONArray) getSession().getAttribute("Visitors_User_List");
        if (list == null)
            return "redirect:/visitors/login.html?name=" + name;
        JSONArray product = null;
        try {
            product = productService.getUserAll(tempS[0]);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("信息异常", e);
        }
        if (product == null)
            return "redirect:/visitors/login.html?name=" + name;
        Iterator<Object> iterator = product.iterator();
        JSONArray jsonArray = new JSONArray();
        while (iterator.hasNext()) {
            JSONObject jsonObject = (JSONObject) iterator.next();
            String productName = jsonObject.getString("name");
            if (list.contains(productName))
                jsonArray.add(jsonObject);
        }
        setAttribute("array", jsonArray);
        setAttribute("pName", name);
        return "visitors/index";
    }

    @RequestMapping(value = "list.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    @NotLogin
    public String list(String productName, String name) {
        productName = convertFilePath(productName);
        name = convertFilePath(name);
        String sKey = StringUtil.convertNULL(getSessionAttribute("Visitors_User"));
        if (StringUtil.isEmpty(sKey))
            return "redirect:/visitors/login.html?name=" + name;
        String[] tempS = StringUtil.stringToArray(sKey, "@");
        if (tempS == null || tempS.length != 2)
            return "redirect:/visitors/login.html?name=" + name;
        if (!name.equals(tempS[0]))
            return "redirect:/visitors/login.html?name=" + name;
        JSONObject jsonOrder;
        try {
            jsonOrder = orderService.getProductOperColumn(tempS[0], productName);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            return "redirect:/visitors/login.html?name=" + tempS[0];
        }
        if (jsonOrder == null)
            return "redirect:/visitors/login.html?name=" + tempS[0];
        setAttribute("columns", jsonOrder.getJSONArray("columns"));
        setAttribute("auth", getSession().getAttribute("Visitors_User_Auth"));
        return "visitors/list";
    }

    @RequestMapping(value = "list_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String listData(String productName, String pageNo, String date, String pageSize, String type) {
        productName = convertFilePath(productName);
        int pageNoInt = StringUtil.parseInt(pageNo, 1);
        int pageSizeInt = StringUtil.parseInt(pageSize, 10);
        // 验证session
        String sKey = StringUtil.convertNULL(getSessionAttribute("Visitors_User"));
        if (StringUtil.isEmpty(sKey))
            return JsonMessage.getString(100, "获取失败");
        String[] tempS = StringUtil.stringToArray(sKey, "@");
        if (tempS == null || tempS.length != 2)
            return JsonMessage.getString(100, "获取失败，错误");
        // 验证产品信息
        JSONArray list = (JSONArray) getSession().getAttribute("Visitors_User_List");
        if (list == null)
            return JsonMessage.getString(100, "请重新登录");
        if (!list.contains(productName))
            return JsonMessage.getString(100, "请检查登录信息");
        return orderService.doSelect(tempS[0], productName, pageNoInt, pageSizeInt, type, 0, date, null, coverInfoHashMap);
    }


    @RequestMapping(value = "ad_type.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String getAd(String name) {
        name = convertFilePath(name);
        String sKey = StringUtil.convertNULL(getSessionAttribute("Visitors_User"));
        if (StringUtil.isEmpty(sKey))
            return JsonMessage.getString(100, "获取失败");
        String[] tempS = StringUtil.stringToArray(sKey, "@");
        if (tempS == null || tempS.length != 2)
            return JsonMessage.getString(100, "获取失败，错误");
        return orderService.getAdType(tempS[0], name);
    }

    /**
     * 作废
     *
     * @param product
     * @param id
     * @return
     */
    @RequestMapping(value = "zf.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String zf(String product, String id, String ids) {
        JSONObject jsonObject = (JSONObject) getSession().getAttribute("Visitors_User_Auth");
        if (jsonObject == null)
            return JsonMessage.getString(100, "没有权限");
        boolean del = jsonObject.getBooleanValue("del");
        if (!del)
            return JsonMessage.getString(100, "没有权限");
        product = convertFilePath(product);
        String sKey = StringUtil.convertNULL(getSessionAttribute("Visitors_User"));
        if (StringUtil.isEmpty(sKey))
            return JsonMessage.getString(100, "获取失败");
        String[] tempS = StringUtil.stringToArray(sKey, "@");
        if (tempS == null || tempS.length != 2)
            return JsonMessage.getString(100, "获取失败，错误");
        String name = tempS[0];
        //name = convertFilePath(name);
        String tableName = getTableName(name, product);
        if (StringUtil.isEmpty(tableName))
            return JsonMessage.getString(405, "作废失败:-100");
        if (StringUtil.isEmpty(id) && !StringUtil.isEmpty(ids)) {
            String tempIds = StringUtil.filterHTML(ids);
            if (!ids.equals(tempIds))
                return JsonMessage.getString(400, "信息不正确，请检查ids");
        }
        return orderService.zf(tableName, id, ids, 1);
    }
}
